/*
 * Copyright (C) Michael Martin & Antonio Carrozzini (TBJD)
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

package org.tbjd.client.listeners.ganttResourceItem;

import java.util.HashMap;
import java.util.Map;

import org.tbjd.client.constants.NotificationsConstants;
import org.tbjd.client.exceptions.TBJDException;
import org.tbjd.client.exceptions.NoUpperDecisionmakerFoundException;
import org.tbjd.client.exceptions.NoUpperMediatorFoundException;
import org.tbjd.client.interfaces.Decisionmaker;

import com.google.gwt.user.client.ui.ChangeListener;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

public class GanttResourceItemRatioChangeListener implements ChangeListener, Decisionmaker {
	
	private Widget sender = null;
	private int ratio;

	public void onChange(Widget sender) {
		this.ratio = Integer.parseInt(((TextBox)sender).getText());
		System.out.println("GanttResourceItemRatioChangeListener.onChange() new ratio="+this.ratio);
		decide(sender);
	}

	public void decide(Object action) {
		System.out.println("GanttResourceItemRatioChangeListener.decide()");

		this.sender = (Widget)action;
		
		// create a map with the add resource key
		Map<Integer, Integer> map = new HashMap<Integer, Integer>();
		map.put(NotificationsConstants.TASK_RESOURCES_RATIOCHANGED, this.ratio);

		// and notify chief
		try {
			delegate(map);
		} catch (NoUpperDecisionmakerFoundException e) {
			e.printStackTrace();
		} catch (NoUpperMediatorFoundException e) {
			e.printStackTrace();
		}
	}

	public void delegate(Object action) throws NoUpperDecisionmakerFoundException, NoUpperMediatorFoundException {
		System.out.println("GanttResourceItemRatioChangeListener.delegate()");

		// passes info to the first responsible
		Widget parent = ((Widget) this.sender).getParent();
		while (parent != null && parent instanceof Decisionmaker == false) {
			parent = ((Widget) parent).getParent();
		}
		if (parent != null) {
			try {
				((Decisionmaker) parent).decide(action);
			} catch (TBJDException e) {
				e.printStackTrace();
			}
		} else {
			throw new NoUpperDecisionmakerFoundException();
		}
	}

	public void handle(Object action) {
	}

}
